package com.wjerp.tplus.server.common.security;

import com.wjerp.tplus.server.common.constant.RolePermission;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * @author lishuailei
 */
public class CustomRoleVoter extends RoleVoter {
	@Override
	public int vote(Authentication authentication, Object object,
                    Collection<ConfigAttribute> attributes) {
		if(authentication == null) {
			return ACCESS_DENIED;
		}
		int result = ACCESS_ABSTAIN;
		Collection<? extends GrantedAuthority> authorities = extractAllAuthorities(authentication);

		for (ConfigAttribute attribute : attributes) {
 			if (this.supports(attribute)) {
				result = ACCESS_ABSTAIN;

				// Attempt to find a matching granted authority
				for (GrantedAuthority authority : authorities) {
					if (attribute.getAttribute().equals(authority.getAuthority())) {
						return ACCESS_GRANTED;
					}
				}
				
				if(attribute.getAttribute().equals(RolePermission.ANONYMOUS.getKey())){
					return ACCESS_GRANTED;
				}
			}
		}

		return result;
	}
	
	Collection<? extends GrantedAuthority> extractAllAuthorities(
			Authentication authentication) {
		return authentication.getAuthorities();
	}
}
